package stark.app.function.wifi;
import stark.common.basic.utils.BroadcastReceiverUtil;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.Utils;

import androidx.lifecycle.MutableLiveData;

/**
 * Author：daizhongbin on 2022/4/28
 * Email：1027154338@qq.com
 * Desc:
 */
public class WifiStateObserver extends BroadcastReceiver {

    private static WifiStateObserver sInstance;
    private static MutableLiveData<Boolean> sWifiStateLiveData = new MutableLiveData<>();

    private WifiStateObserver() {
        sWifiStateLiveData.setValue(NetworkUtils.getWifiEnabled());
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
        if (state == WifiManager.WIFI_STATE_ENABLED) {
            sWifiStateLiveData.setValue(true);
        } else if (state == WifiManager.WIFI_STATE_DISABLED || state == WifiManager.WIFI_STATE_DISABLING) {
            sWifiStateLiveData.setValue(false);
        }
    }

    /**
     * 开始监听
     */
    public static void startListen() {
        if (sInstance == null) {
            sInstance = new WifiStateObserver();
            BroadcastReceiverUtil.registerReceiver(Utils.getApp(), sInstance, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
        }
    }

    /**
     * 停止监听
     */
    public static void stopListen() {
        if (sInstance != null) {
            Utils.getApp().unregisterReceiver(sInstance);
            sInstance = null;
        }
    }

    public static MutableLiveData<Boolean> getWifiStateLiveData() {
        return sWifiStateLiveData;
    }
}
